/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.commonres.widget;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import io.ganguo.library.mvp.util.UIUtils;

/**
 * TextView里面全尺寸显示图片
 * <p/>
 * Created by Tony on 4/30/15.
 */
public class FullSizeImageGetter implements Html.ImageGetter {
    TextView mTextView;
    private int sourceWidth;

    public FullSizeImageGetter(TextView textView) {
        this(textView, UIUtils.getDisplayWidth());
    }

    public FullSizeImageGetter(TextView textView, int sourceWidth){
        this.mTextView = textView;
        this.sourceWidth = sourceWidth;
    }

    @Override
    public Drawable getDrawable(String source) {
        final UrlDrawable urlDrawable = new UrlDrawable();
        Glide.with(mTextView.getContext())
                .asBitmap()
                .load(source)
                .into(new BitmapTarget(urlDrawable));

        return urlDrawable;
    }

    private class BitmapTarget extends SimpleTarget<Bitmap> {
        private final UrlDrawable urlDrawable;

        public BitmapTarget(UrlDrawable urlDrawable) {
            this.urlDrawable = urlDrawable;
        }

        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            Drawable drawable = new BitmapDrawable(mTextView.getContext().getResources(), resource);
            float picW = drawable.getIntrinsicWidth();
            float picH = drawable.getIntrinsicHeight();
            Rect rect = new Rect(0, 0, sourceWidth, (int) ((picH / picW) * sourceWidth));
            drawable.setBounds(rect);

            urlDrawable.setDrawable(drawable);
            urlDrawable.setBounds(rect);

            // i don't know yet a better way to refresh TextView
            // mTv.invalidate() doesn't work as expected
            mTextView.invalidate();
//            mTextView.setText(mTextView.getText());
        }
    }

    private static final class UrlDrawable extends BitmapDrawable {
        private Drawable drawable;

        @SuppressWarnings("deprecation")
        UrlDrawable(){
        }

        @Override
        public void draw(Canvas canvas) {
            if (drawable != null) {
                drawable.draw(canvas);
            }
        }

        public void setDrawable(Drawable drawable) {
            this.drawable = drawable;
        }
    }
}
